package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.StudentInfo;
import com.ruoyi.system.service.IStudentInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生信息Controller
 *
 * @author ltr
 * @date 2024-10-21
 */
@RestController
@RequestMapping("/system/student")
public class StudentInfoController extends BaseController
{
    @Autowired
    private IStudentInfoService studentInfoService;

    // ==================== 原有功能（学生个人端） ====================

    /**
     * 查询学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:student:list')")
    @GetMapping("/list")
    public TableDataInfo list(StudentInfo studentInfo)
    {
        startPage();
        List<StudentInfo> list = studentInfoService.selectStudentInfoList(studentInfo);
        return getDataTable(list);
    }

    /**
     * 导出学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:student:export')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StudentInfo studentInfo)
    {
        List<StudentInfo> list = studentInfoService.selectStudentInfoList(studentInfo);
        ExcelUtil<StudentInfo> util = new ExcelUtil<StudentInfo>(StudentInfo.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 获取学生信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:student:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId)
    {
        return success(studentInfoService.selectStudentInfoByStudentId(studentId));
    }

    /**
     * 根据用户ID获取学生信息
     */
    @GetMapping(value = "/user/{userId}")
    public AjaxResult getInfoByUserId(@PathVariable("userId") Long userId)
    {
        return success(studentInfoService.selectStudentInfoByUserId(userId));
    }

    /**
     * 获取当前登录学生的信息
     */
    @GetMapping("/profile")
    public AjaxResult getProfile()
    {
        Long userId = getUserId();
        StudentInfo studentInfo = studentInfoService.selectStudentInfoByUserId(userId);
        return success(studentInfo);
    }

    /**
     * 新增学生信息（原有的简单新增）
     */
    @PreAuthorize("@ss.hasPermi('system:student:add')")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StudentInfo studentInfo)
    {
        return toAjax(studentInfoService.insertStudentInfo(studentInfo));
    }

    /**
     * 修改学生信息
     */
    @PreAuthorize("@ss.hasPermi('system:student:edit')")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StudentInfo studentInfo)
    {
        return toAjax(studentInfoService.updateStudentInfo(studentInfo));
    }

    /**
     * 保存或更新学生信息（个人中心使用）
     */
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping("/profile")
    public AjaxResult saveOrUpdate(@RequestBody StudentInfo studentInfo)
    {
        // 设置当前用户ID
        studentInfo.setUserId(getUserId());
        return toAjax(studentInfoService.saveOrUpdateStudentInfo(studentInfo));
    }

    /**
     * 删除学生信息
     */
    @PreAuthorize("@ss.hasPermi('system:student:remove')")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds)
    {
        return toAjax(studentInfoService.deleteStudentInfoByStudentIds(studentIds));
    }

    // ==================== 新增：管理员端功能 ====================

    /**
     * 新增学生信息并自动创建系统账号（管理员端）
     */
    @PreAuthorize("@ss.hasPermi('system:student:add')")
    @Log(title = "新增学生（创建账号）", businessType = BusinessType.INSERT)
    @PostMapping("/addWithAccount")
    public AjaxResult addWithAccount(@Validated @RequestBody StudentInfo studentInfo)
    {
        // 校验学号是否已存在
        if (!studentInfoService.checkStudentNoUnique(studentInfo))
        {
            return error("新增学生'" + studentInfo.getStudentNo() + "'失败，学号已存在");
        }

        studentInfo.setCreateBy(getUsername());
        return toAjax(studentInfoService.insertStudentInfoWithAccount(studentInfo));
    }

    /**
     * 批量导入学生信息（自动创建系统账号）
     */
    @PreAuthorize("@ss.hasPermi('system:student:import')")
    @Log(title = "批量导入学生", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<StudentInfo> util = new ExcelUtil<StudentInfo>(StudentInfo.class);
        List<StudentInfo> studentList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = studentInfoService.importStudentInfo(studentList, updateSupport, operName);
        return success(message);
    }

    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<StudentInfo> util = new ExcelUtil<StudentInfo>(StudentInfo.class);
        util.importTemplateExcel(response, "学生信息数据");
    }

    /**
     * 重置学生账号密码为123456
     */
    @PreAuthorize("@ss.hasPermi('system:student:resetPwd')")
    @Log(title = "重置学生密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd/{studentId}")
    public AjaxResult resetPwd(@PathVariable Long studentId)
    {
        return toAjax(studentInfoService.resetStudentPassword(studentId, getUsername()));
    }
}